<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/4/30
 * Time: 16:06
 */
namespace app\alipay\controller;

use app\alipay\model\ConsumeManager;
use app\common\model\Base;
use app\shopping\model\Commdetailstool;
use app\shopping\model\Indent;
use think\Config;
use think\Db;
use think\Log;

class Pay extends Indent{

    private $commdetailstool;
    public function __construct()
    {
        parent::__construct();
        Config::load(APP_PATH . 'alipay/config.php');
    }

    /**
     *
     * @api {get} /alipay/pay  支付宝支付
     * @apiDescription 支付宝支付
     * @apiGroup alipay
     * @apiVersion 0.1.0
     * @apiParam {string} uid 用户ID
     * @apiParam {string} indent_id 订单ID
     * @apiParam {string} total_prices 总价格
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "uid": 17754928306，
     *       "indent_id": 123456789，
     *       "total_prices":"xxx"
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 消息.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "xxx"
     *     }
     */
    public function index(){
        //var_dump(config::get("alipay_config")) ;
        //var_dump(config('alipay.notify_url'));
        $this->commdetailstool = new Commdetailstool();

        $uid=$_GET["uid"];
        $out_trade_no = $_GET["indent_id"];
        if(!$this->check->isUidExist($uid))
        {
            echo echoJson(0, "用户不存在！");
            exit;
        }

        $order = $this->getIndentfromid($uid,$out_trade_no);
        //$order = $this->getIndent($uid);
        if($order){
            //logout($order);
            $total_amount = $order["total_prices"];
            $this->doalipay($uid,$out_trade_no,$total_amount/500);
            //$this->dowebalipay($uid,$out_trade_no,$total_amount/500);
            //logout($total_amount);
        }else{
            echo echoJson(0,"订单不存在" );
        }
        /*if($order){

            $this->dowebalipay($uid,$out_trade_no,$total_amount);
        }else{
            echo echoJson(0,"订单不存在" );
        }*/

        //logout($total_amount);
        //$out_trade_no = $_GET["indent_id"];




        //var_dump(config('alipay_config'));
        //if(!$this->check->isPayNull($uid,$subject,$total_amount))
        //    return;
        //$subject=$_GET["goods"];
        //$total_amount=$_GET["total_amount"];
        //$this->dowebalipay($uid,$subject,$total_amount);
    }

    public function dowebalipay($uid,$out_trade_no,$total_amount){
        header('Access-Control-Allow-Origin: *');
        header('Content-type: text/plain');

        include EXTEND_PATH.'alipay-sdk/AopSdk.php';

        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = "2018042102588421";
        $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDmn4YP9XmbFToB/vghSCsnv0ro52zgpeAfkqTnG7XFhnTdGvPDVuOjXaoDR9kIBOa1U2TfdV728MqoZCqAZSAJ+rw28+StL8y3x+thn5rf2j7jb5oXu9kMlMh5FHGaU8tVwgrEG12krEiquH5D9hn57OGlk3LvvTAZyNOkMQxxIkzBH2hnPtjax8upaAOOj4MZ3QckNlAjOglqQDBWOPiU7EE0KXwxW6h3pHEz8WPBI+nh3X1UpFCClmZaPGLLLTvPletfPWCYpFc3d6YMMiMhmES5z/MO9pLOjp3grBXN+A67hG805Xsk/CPEcbUsJv/usvkCcYRVxA/f14ZwAQHLAgMBAAECggEBAMR/55pxbcvVqjdJJ+Izu5GCTDFl/j7rFqvQJvFDiv1iMvCxpkEqJ4tqoxFohmNuyaR2CdzcBK4jPIl9zzjW8RWPrg6kgJOPxr5QeR4U/8D8E9l1nbXbOHSf0LBZ2vHDs9y+GK4/IurMYJ4V1H/TkQ6B50FNAQGEERfnJW0g3ZkGImaSwKYCjEW3sgx4uRnXVsYOm7z97O+kTGhoNsn0zppvpF5dZni/164Znnm3XZ4aym3Z+gBYA1Z/PI0tqnLuixtWj9AVe6XtOhl0mfHMBU2lM6H+USMTa6Rec4MheSJCUFqXMD2O99XgbizhK4/OYeDwR0NoedKZyR5jJua+YAECgYEA+dd2eZG7miehQYRGwHc5bK4Jtv3GfnqJIjxoSA9Yi67V0TL85ihv6VC0qscO+LaBpwYkO9YE2Z3Io/6g9j6ZOFaiaBy2ZDItOTZ2UaVj+h0CqtQmDwFiZyzyO5OtDNyJtNpEpC/wBotdC9RXy3Ia45lcSoob6AiWMJw4E77od4ECgYEA7E7KDh2HtX4sAWWhdOK9lcXgp64FaZU/OZGnpSZBSOLeQUnI84fwOB6kT6cGsaekkb7zBYSzsVzL6VMNKJ896CPa0LCIGxUmbe1tEZ8c1bf0zof7z6eZF0bmp2Q54XZd1baGA9iCx+f/UDYn4nXbeGTOWuece1DBxS/C7SUdf0sCgYEAnDSxdzq9j5k9gigA0G76cU+y9T1fsE5OlSAtlvg5RUQvnReC9SfNKJP0EV5Zpvj8wP/fAaZC7AhxnM8jtjHXPFk2O1/QTX7ttXquqUd95a/jrgjsLq+P5bA9VzBynrr4QiHBjuIF8SGLME04AxQ5aZnGETieUAmmVYgmq3nOAIECgYEAjBt274GQugox+y4P2aaqM4gcWC70pJJJ508179RLtvRURK+DxuidhBie4V8tt92m1Ic7vdTdWdakTBXi4mfwI5hGn59bQ3t5yomQNnd5eDnWmzHDGm7LdSKjlTH2o3gz0Iek09jmSbKDDULeyQWJ98sFEp7qh67tBIX58/MilxsCgYB3XTnPQdx76E+lBdiRbuvkjx5XJVEB5NoUsOLRpg0lyhNNLNqB5BwjVpYbF29fyLUdaLYsz82Vxbg+SeaQfI9hAFjmgho7kCgrcH8tphK7MXAR77gXMZXMILnhdM3qM6pM3R/RnQrGiHOaQgVL9/mMtcjeB1yBgXQpoeBPf0g4GA==';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5p+GD/V5mxU6Af74IUgrJ79K6Ods4KXgH5Kk5xu1xYZ03Rrzw1bjo12qA0fZCATmtVNk33Ve9vDKqGQqgGUgCfq8NvPkrS/Mt8frYZ+a39o+42+aF7vZDJTIeRRxmlPLVcIKxBtdpKxIqrh+Q/YZ+ezhpZNy770wGcjTpDEMcSJMwR9oZz7Y2sfLqWgDjo+DGd0HJDZQIzoJakAwVjj4lOxBNCl8MVuod6RxM/FjwSPp4d19VKRQgpZmWjxiyy07z5XrXz1gmKRXN3emDDIjIZhEuc/zDvaSzo6d4KwVzfgOu4RvNOV7JPwjxHG1LCb/7rL5AnGEVcQP39eGcAEBywIDAQAB';
        $aop->apiVersion = '1.0';
        $request = new \AlipayTradeWapPayRequest ();

        $request->setBizContent("{" .
            "    \"body\":\"".$uid."\"," .
            "    \"subject\":\"上医道元商品支付\"," .
            "    \"out_trade_no\":\"".$out_trade_no.'-'.time()."\"," .
            "    \"timeout_express\":\"90m\"," .
            "    \"total_amount\":".$total_amount."," .
            "    \"product_code\":\"QUICK_WAP_WAY\"" .
            "  }");
        $request->setNotifyUrl("http://www.topsydy.com/app/sydy/alipay/pay/notifyurl");
        $request->setReturnUrl("http://www.topsydy.com/app/sydy/alipay/pay/returnurl");
        $result = $aop->pageExecute($request);
        echo $result;
    }

    //doalipay方法
    /*该方法其实就是将接口文件包下alipayapi.php的内容复制过来
      然后进行相关处理
    */

    /**
     * 支付宝调用接口及其参数
     * url:http://www.idolly.com/pay/pay/doalipay
     * Para:
     *      out_trade_no         商户订单号 //必填  ，注意要唯一！
     *      subject              订单名称 //必填
     *      total_fee             //付款金额  //必填
     *      body                  订单描述，//选填
     *      userid                用户ID   //必填
     *      username              用户人姓名  //必填
     */
    public function doalipay($uid,$out_trade_no,$total_amount){
        header('Access-Control-Allow-Origin: *');
        header('Content-type: text/plain');

        include EXTEND_PATH.'alipay-sdk/AopSdk.php';


        $aop = new \AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2018053160282375";
        $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDmn4YP9XmbFToB/vghSCsnv0ro52zgpeAfkqTnG7XFhnTdGvPDVuOjXaoDR9kIBOa1U2TfdV728MqoZCqAZSAJ+rw28+StL8y3x+thn5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bA9VzBynrr4QiHBjuIF8SGLME04AxQ5aZnGETieUAmmVYgmq3nOAIECgYEAjBt274GQugox+y4P2aaqM4gcWC70pJJJ508179RLtvRURK+DxuidhBie4V8tt92m1Ic7vdTdWdakTBXi4mfwI5hGn59bQ3t5yomQNnd5eDnWmzHDGm7LdSKjlTH2o3gz0Iek09jmSbKDDULeyQWJ98sFEp7qh67tBIX58/MilxsCgYB3XTnPQdx76E+lBdiRbuvkjx5XJVEB5NoUsOLRpg0lyhNNLNqB5BwjVpYbF29fyLUdaLYsz82Vxbg+SeaQfI9hAFjmgho7kCgrcH8tphK7MXAR77gXMZXMILnhdM3qM6pM3R/RnQrGiHOaQgVL9/mMtcjeB1yBgXQpoeBPf0g4GA==';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5p+GD/V5mxU6Af74IUgrJ79K6Ods4KXgH5Kk5xu1xYZ03Rrzw1bjo12qA0fZCATmtVNk33Ve9vDKqGQqgGUgCfq8NvPkrS/Mt8frYZ+a39o+42+aF7vZDJTIeRRxmlPLVcIKxBtdpKxIqrh+Q/YZ+ezhpZNy770wGcjTpDEMcSJMwR9oZz7Y2sfLqWgDjo+DGd0HJDZQIzoJakAwVjj4lOxBNCl8MVuod6RxM/FjwSPp4d19VKRQgpZmWjxiyy07z5XrXz1gmKRXN3emDDIjIZhEuc/zDvaSzo6d4KwVzfgOu4RvNOV7JPwjxHG1LCb/7rL5AnGEVcQP39eGcAEBywIDAQAB';
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        /*$bizcontent = "{\"body\":\"商品信息\","
            . "\"subject\": \"上医道元商品支付\","
            . "\"out_trade_no\": \"".$out_trade_no.'-'.time()."\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";*/
        /*$request->setBizContent("{" .
            "    \"body\":\"".$uid."\"," .
            "    \"subject\":\"上医道元商品支付\"," .
            "    \"out_trade_no\":\"".$out_trade_no.'-'.time()."\"," .
            "    \"timeout_express\":\"90m\"," .
            "    \"total_amount\":0.01," .
            "    \"product_code\":\"QUICK_MSECURITY_PAY\"" .
            "  }");*/
        $bizcontent = json_encode([
            'body'=>'商品信息',
            'subject'=>'上医道元商品支付',
            'out_trade_no'=> $out_trade_no.'-'.time(),//此订单号为商户唯一订单号
            'total_amount'=> $total_amount,//保留两位小数
            'product_code'=>'QUICK_MSECURITY_PAY'
        ]);
        $request->setNotifyUrl("http://www.topsydy.com/app/sydy/alipay/pay/notifyurl");
        $request->setReturnUrl("http://www.topsydy.com/app/sydy/alipay/pay/returnurl");
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        echo $response;//htmlspecialchars($response);//htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
        exit;
    }


    /******************************
    服务器异步通知页面方法
    其实这里就是将notify_url.php文件中的代码复制过来进行处理

     *******************************/
    function notifyurl(){
        /*
        同理去掉以下两句代码；
        */
        //require_once("alipay.config.php");
        //require_once("lib/alipay_notify.class.php");

        $arr=$_POST;
        //$alipaySevice = new \AlipayTradeService(config('alipay'));
        //$alipaySevice->writeLog(var_export($_POST,true));
        //$result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        Log::write("loghere".var_dump($arr));
        if(1) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            $out_trade_no = $_POST['out_trade_no'];
            $trade_no = $_POST['trade_no'];
            $trade_status = $_POST['trade_status'];



            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                $out_trade_no   = $_POST['out_trade_no'];
                $out_trade_no = strstr($out_trade_no, '-', TRUE);
                //这里还是通过C函数来读取配置项，赋值给$alipay_config
                $sql = "update sopp_indent set indent_state='2' where indent_id='$out_trade_no'";
                $this->mysql->updateSQL($sql);

                $sql = "select uid from sopp_indent where indent_id='$out_trade_no'";
                $result = $this->mysql->selectSQLRow($sql);
                Log::write($result);
                Log::write($_POST['total_amount']);
                $consumeManager = new ConsumeManager();
                $consumeManager->updateConsumeRecord($result['uid'],$_POST['total_amount']);
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除

        }else {
            //验证失败
            echo "fail";	//请不要修改或删除

        }
        echo "success";
    }

    /*
        页面跳转处理方法；
        这里其实就是将return_url.php这个文件中的代码复制过来，进行处理；
        */

    function returnurl(){
        //头部的处理跟上面两个方法一样，这里不罗嗦了！
        $arr=$_GET;
        //$alipaySevice = new \AlipayTradeService(config('alipay'));
        //$result = $alipaySevice->check($arr);
        //var_dump($result);
        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(1) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

            //商户订单号

            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);

            //支付宝交易号

            $trade_no = htmlspecialchars($_GET['trade_no']);

            echo "验证成功<br />外部订单号：".$out_trade_no;
            var_dump($arr);
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            //验证失败
            echo "验证失败";
        }
    }
}